package com.tuanzi.controller;


import com.tuanzi.beans.HttpResponseEntity;
import com.tuanzi.common.Constans;
import com.tuanzi.service.InformationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


@RestController
public class InformationController {
    private final Logger logger = LoggerFactory.getLogger(InformationController.class);

    @Autowired
    private InformationService informationService;



    @RequestMapping(value = "/import")
    public HttpResponseEntity fileImport(@RequestParam("file") MultipartFile file)throws Exception{

        HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
        try {
            if (!checkFileSize(file,1048575,"B")){
                logger.error("上传文件过大");
            }
            String fileName = file.getOriginalFilename();
            informationService.getExcelInfo(fileName,file);
            httpResponseEntity.setCode(Constans.SUCCESS_CODE);
        } catch (Exception e) {
            e.printStackTrace();
            httpResponseEntity.setCode(Constans.ADD_EXIST_CODE);
        }
        return httpResponseEntity;
    }

    public boolean checkFileSize(MultipartFile multipartFile, int size, String unit){
        long len = multipartFile.getSize();
        double fileSize = 0;
        if ("B".equals(unit.toUpperCase())){
            fileSize = (double)len;

        }else if ("K".equals(unit.toUpperCase())){
            fileSize = (double)len / 1024;
        } else if ("M".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1048576;
        } else if ("G".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1073741824;
        }
        //如果上传文件大于限定的容量
        if (fileSize > size) {
            return false;
        }
        return true;
    }
}
